package com.shengcheng.service.impl;

import com.shengcheng.constant.SystemConstant;
import com.shengcheng.entity.RechargeInfo;
import com.shengcheng.entity.UserAccountDetail;
import com.shengcheng.mapper.RechargeInfoMapper;
import com.shengcheng.mapper.UserAccountMapper;
import com.shengcheng.service.RechargeInfoService;
import com.shengcheng.service.UserAccountDetailService;
import com.shengcheng.util.AuthContextHolder;
import com.shengcheng.vo.RechargeInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 充值信息 服务实现类
 * </p>
 *
 * @author 强哥
 * @since 2023-12-16
 */
@Service
public class RechargeInfoServiceImpl extends ServiceImpl<RechargeInfoMapper, RechargeInfo> implements RechargeInfoService {
    @Autowired
    private UserAccountDetailService accountDetailService;
    @Override
    public Map<String, Object> saveRecharge(RechargeInfoVo rechargeInfoVo) {
        Long userId = AuthContextHolder.getUserId();
        RechargeInfo rechargeInfo = new RechargeInfo();
        rechargeInfo.setUserId(userId);
        rechargeInfo.setOrderNo(UUID.randomUUID().toString().replaceAll("-",""));
        rechargeInfo.setRechargeStatus(SystemConstant.ORDER_UNPAID);
        rechargeInfo.setRechargeAmount(rechargeInfoVo.getAmount());
        rechargeInfo.setPayWay(rechargeInfoVo.getPayWay());
        save(rechargeInfo);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("orderNo",rechargeInfo.getOrderNo());
        return retMap;
    }

    @Autowired
    private UserAccountMapper userAccountMapper;
    @Override
    public void rechargePaySuccess(String orderNo) {
        RechargeInfo rechargeInfo = getOne(new LambdaQueryWrapper<RechargeInfo>().eq(RechargeInfo::getOrderNo, orderNo));
        if(SystemConstant.ORDER_PAID.equals(rechargeInfo.getRechargeStatus())) return;
        rechargeInfo.setRechargeStatus(SystemConstant.ORDER_PAID);
        updateById(rechargeInfo);
        //添加账号明细
        UserAccountDetail userAccountDetail= new UserAccountDetail();
        userAccountDetail.setUserId(rechargeInfo.getUserId());
        userAccountDetail.setTitle("充值");
        userAccountDetail.setTradeType(SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT);
        userAccountDetail.setAmount(rechargeInfo.getRechargeAmount());
        userAccountDetail.setOrderNo(orderNo);
        accountDetailService.save(userAccountDetail);
        //添加账户金额
        userAccountMapper.addRechargeAmount(rechargeInfo.getUserId(),rechargeInfo.getRechargeAmount());

    }
}
